/*
 * 
 * LegendShop 多用户商城系统
 * 
 *  版权所有,并保留所有权利。
 * 
 */
package com.legendshop.permission.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import com.legendshop.oa.model.Menu;
import com.legendshop.oa.model.RoleMenu;
import com.legendshop.permission.dao.MenuManagerDao;

/**
 * The Class MenuManagerDaoImpl.
 */
public class MenuManagerDaoImpl implements MenuManagerDao {
	
	/** The jdbc template. */
	private JdbcTemplate jdbcTemplate;
	
	private String sqlForGetMenu = "select * from ls_menu order by grade,seq";
	
	private String sqlForGetRoleMenu = "SELECT f.menu_id,p.role_id,r.role_type AS role_name FROM ls_role r,ls_perm p,ls_func f WHERE r.id = p.role_id AND f.id = p.function_id AND f.menu_id IS NOT NULL ORDER BY f.menu_id";
	
	/**
	 * 获取所有可用的菜单
	 */
	@Override
	public List<Menu> getMenu() {
		List<Menu> menuList = jdbcTemplate.query(sqlForGetMenu, new MenuRowMapper());
		return menuList;
	}
	
	/**
	 * 获取每个Role所拥有的菜单的全集
	 */
	@Override
	public List<RoleMenu> getRoleMenu() {
		return  jdbcTemplate.query(sqlForGetRoleMenu, new RoleMenuMapper());
	}


	private class MenuRowMapper implements RowMapper<Menu>{

		@Override
		public Menu mapRow(ResultSet rs, int rowNum) throws SQLException {
			Menu menu = new Menu();
			menu.setAction(rs.getString("action"));
			menu.setLabel(rs.getString("label"));
			menu.setGrade(rs.getInt("grade"));
			menu.setMenuId(rs.getLong("menu_id"));
			menu.setName(rs.getString("name"));
			menu.setSeq(rs.getInt("seq"));
			long pId = rs.getLong("parent_id");
			menu.setParentId(pId == 0 ? null : pId);
			menu.setProvidedPlugin(rs.getString("provided_plugin"));
			menu.setTitle(rs.getString("title"));
			return menu;
		}
		
	}
	
	private class RoleMenuMapper implements RowMapper< RoleMenu>{

		@Override
		public RoleMenu mapRow(ResultSet rs, int rowNum) throws SQLException {
			RoleMenu roleMenu = new RoleMenu();
			roleMenu.setMenuId(rs.getLong("menu_id"));
			roleMenu.setRoleId(rs.getString("role_id"));
			roleMenu.setRoleName(rs.getString("role_name"));
			return roleMenu;
		}
	}
	
	/**
	 * @param jdbcTemplate the jdbcTemplate to set
	 */
	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}


}
